<?php

namespace App\Extend;
use App\Models\AirwallexPayRecord;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;

/**
 * undocumented class
 *
 * @package default
 * @author
 **/
class Airwallex
{
    const TOKEN_CACHE_KEY = 'airwallex:token';
    protected $apiUrl = 'https://api.airwallex.com';
    protected $clientId = 'PDepJwYpTrOeFWp0yf-tVQ';
    protected $appKey = '9e4808912af43e77c601c2d0608f24bafb2768b8180bda77378caac7cf63252da909c53e1572bcb679753263cf3d1a12';

    protected $webhookKey = 'whsec_ar76zq_zRQaSZQ-cHNSsvVS9PcOK6hQC';

    /**
     * Get account detail information
     *
     * @return string
     * @author
     **/
    public function getToken(): string
    {
        $token = Cache::get(self::TOKEN_CACHE_KEY);
        if (!empty($token)) {
            return $token;
        }
        $apiUrl = $this->apiUrl . '/api/v1/authentication/login';
        $response = Http::withHeaders([
            'Content-Type' => 'application/json',
            'x-api-key' => $this->appKey,
            'x-client-id' => $this->clientId
        ])->post($apiUrl);
        $result = $response->json();
        Cache::put(self::TOKEN_CACHE_KEY, $result['token'], 1800);
        return $result['token'];
    }

    /**
     * Get account detail information
     *
     * @return array|false
     * @author
     **/
    public function createPayment($user_info, $amount, $merchant_order_id, $desc, $currency = 'USD', $return_url = '', $metadata = [])
    {
        $token = $this->getToken();
        $request_id = Str::random(16);
        $params = [
            'request_id' => $request_id,
            'amount' => $amount,
            'currency' => $currency,
            'merchant_order_id' => $merchant_order_id,
            'return_url' => $return_url,
            'descriptor' => $desc,
            'customer' => [
                'first_name' => $user_info['first_name'],
                'last_name' => $user_info['last_name'],
                'email' => $user_info['email'],
                'merchant_customer_id' => $user_info['id']
            ],
            'order' => [
                'products' => [
                    ['name' => $desc]
                ]
            ]
        ];
        if (!empty($metadata)) {
            $params['metadata'] = $metadata;
        }
        $apiUrl = $this->apiUrl . '/api/v1/pa/payment_intents/create';
        $response = Http::withHeaders([
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $token,
        ])->post($apiUrl, $params);
        $result = $response->json();
        AirwallexPayRecord::create([
            'request_id' => $request_id,
            'payment_id' => $result['id'],
            'merchant_order_id' => $merchant_order_id,
            'client_secret' => $result['client_secret'],
            'status' => $result['status'],
        ]);
        return $result;
    }

    public function queryPayment($payment_id)
    {
        $token = $this->getToken();
        $apiUrl = $this->apiUrl . '/api/v1/pa/payment_intents/' . $payment_id;
        $response = Http::withHeaders([
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $token,
        ])->get($apiUrl);
        return $response->json();
    }

    public function getList()
    {
        $token = $this->getToken();
        $apiUrl = $this->apiUrl . '/api/v1/pa/payment_intents';
        $response = Http::withHeaders([
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $token,
        ])->get($apiUrl);
        return $response->json();
    }
} // END class
